<template>
	<view ref="step2Register" class="step-container">
		<view class="card">
			<view class="space-y-20">
				<!-- 使用 u-form 组件包裹所有输入项 -->
				<u-form :model="formData" :rules="rules" ref="uForm" labelWidth="80" labelAlign="right"
					:borderBottom="true">
					<!-- 手机号输入框 -->
					<u-form-item label="手机号" prop="telephone">
						<u-input v-model="formData.telephone" :disabled="true" placeholder="请输入手机号"></u-input>
					</u-form-item>

					<!-- 验证码输入框和按钮 -->
					<u-form-item label="验证码" prop="randNum">
						<u-input v-model="formData.randNum" placeholder="请输入验证码">
							<template slot="suffix">
								<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
								<u-button @tap="getPicFun" :text="tips" type="success" size="mini"></u-button>
							</template>
						</u-input>
					</u-form-item>
					<!-- 身份证号输入框 -->
					<u-form-item label="身份证号" prop="identityCardNo">
						<u-input v-model="formData.identityCardNo" type="idcard" placeholder="身份证号"></u-input>
					</u-form-item>

					<!-- 密码输入框 -->
					<u-form-item label="密码" prop="userPwd">
						<u-input v-model="formData.userPwd" type="password" placeholder="请设置密码" password-icon></u-input>
					</u-form-item>

					<!-- 确认密码输入框 -->
					<u-form-item label="确认密码" prop="confirmPwd">
						<u-input v-model="formData.confirmPwd" type="password" placeholder="请确认密码"
							password-icon></u-input>
					</u-form-item>

					<!-- 提交按钮 -->
					<u-form-item>
						<u-button ref="registerBtn" type="primary" class="action-btn"
							@click="submitForm">重置密码</u-button>
					</u-form-item>
				</u-form>
			</view>
		</view>
		<slider-captcha v-show="isSliderShow" :frontimg="picObj.slidingImage" :backimg="picObj.backImage"
			:yHeight="picObj.yHeight" :maskclose="true" :randNum="telRandom" @onRefresh="getPicFun" @onSuccess="getCode"
			@onClose="handClose" @onMoveEnd="handleSliderMoveEnd" />
	</view>
</template>

<script>
	import {
		getPic,
		checkcapcode,
		postSend
	} from '@/api/api.js'
	import {
		forgetUserInfo
	} from '@/api/loginApi.js'
	import SliderCaptcha from '@/pages/compoents/slideVue.vue';
	import w_md5 from "@/js_sdk/zww-md5/w_md5.js"
	export default {
		components: {
			SliderCaptcha
		},
		data() {
			return {
				isSliderShow: false,
				picObj: {
					slidingImage: '',
					backImage: '',
					capcode: '',
					yHeight: 0
				},
				telRandom: 0, //请求验证码的随机码
				tips: '',
				formData: {
					identityCardNo: '',
					telephone: '',
					randNum: '',
					userPwd: '',
					confirmPwd: ''
				},
				// 校验规则
				rules: {
					identityCardNo: [{
							required: true,
							message: '身份证号不能为空',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								// 18位身份证正则（基本格式）
								const idCardReg =
									/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;

								if (!value) {
									return callback(new Error('请输入身份证号'));
								}

								// 基本格式校验
								if (!idCardReg.test(value)) {
									return callback(new Error('请输入正确的身份证号格式'));
								}

								// 校验码验证（根据GB 11643-1999标准）
								const code = '10X98765432'; // 校验码对应值
								const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
								let sum = 0;
								const idCardUpper = value.toUpperCase(); // 统一转为大写（处理x/X）

								// 计算前17位与加权因子的乘积和
								for (let i = 0; i < 17; i++) {
									sum += parseInt(idCardUpper[i], 10) * factor[i];
								}

								// 计算校验码
								const checkCode = code[sum % 11];
								if (idCardUpper[17] !== checkCode) {
									return callback(new Error('身份证号校验码错误，请检查'));
								}

								// 验证通过
								callback();
							},
							trigger: 'blur'
						}
					],
					telephone: [{
						required: true,
						message: '手机号不能为空',
						trigger: 'blur'
					}, {
						pattern: /^1[3-9]\d{9}$/, // 11位数字，第一位为1，第二位为3-9，后9位为任意数字
						message: '请输入正确的手机号格式',
						trigger: ['blur', 'change']
					}],
					randNum: [{
						required: true,
						message: '验证码不能为空',
						trigger: 'blur'
					}],
					userPwd: [{
						required: true,
						message: '密码不能为空',
						trigger: 'blur'
					},{
  pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/,
  message: '密码必须包含字母和数字，且长度在8-20个字符之间',
  trigger: 'blur'
}],
					confirmPwd: [{
							required: true,
							message: '确认密码不能为空',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								if (value !== this.formData.userPwd) {
									callback(new Error('确认密码与密码不一致'));
								} else {
									callback();
								}
							},
							trigger: 'blur'
						}
					]
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			this.formData.telephone = option.phone
		},
		methods: {
			codeChange(text) {
				this.tips = text;
			},
			async getPicFun() {
				if (!this.formData.telephone) {
					return uni.$u.toast('请输入手机号后再发送');
				}
				if (!this.$refs.uCode.canGetCode) {
					return uni.$u.toast('倒计时结束后再发送');
				}
				try {
					uni.showLoading({
						title: '加载中'
					})
					const res = await getPic(this.formData.telephone)
					console.log('222', res)
					if (res.data.result == 0) {
						this.picObj = {
							...res.data,
							backImage: 'data:image/png;base64,' + res.data.backImage,
							slidingImage: 'data:image/png;base64,' + res.data.slidingImage
						}
						console.log('222', this.picObj)
						this.telRandom = 0 // 打开前重置
						this.isSliderShow = true
						uni.hideLoading()
					} else {
						uni.hideLoading()
						uni.$u.toast(res.data.message || '获取验证码失败！');
					}
				} catch (error) {
					uni.hideLoading()
					uni.$u.toast(res.data.message || '获取验证码失败！');
				}
			},
			async handleSliderMoveEnd(moveX) {
				try {
					const res = await checkcapcode({
						xpos: moveX,
						capcode: this.picObj.capcode,
						mobile: this.formData.telephone
					})
					if (res.data.result == 0) {
						this.telRandom = res.data.randNum
					} else {
						this.telRandom = Math.floor(Math.random() * 1000)
						uni.$u.toast(res.data.message || '验证失败！');
					}
				} catch (error) {
					this.telRandom = Math.floor(Math.random() * 1000)
					uni.$u.toast(res.data.message || '验证失败！');
				}
			},
			async getCode() {
				this.isSliderShow = false
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				try {
					const res = await postSend(this.formData.telephone, this.telRandom)
					if (res.data.result == 0) {
						uni.hideLoading();
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					} else {
						uni.hideLoading();
						uni.$u.toast(res.data.message || '发送短信失败！');
					}
				} catch (error) {
					uni.$u.toast(res.data.message || '发送短信失败！');
				}
			},
			handClose() {
				this.isSliderShow = false
			},
			submitForm() {
				this.$refs.uForm.validate().then(async val => {
					// 校验通过后，执行提交操作
					console.log('表单数据:', this.formData);
					uni.showLoading({
						title: '加载中'
					})
					const params = {
						...this.formData,
						userPwd: w_md5.hex_md5_16(this.formData.userPwd),
						confirmPwd: w_md5.hex_md5_16(this.formData.confirmPwd)
					}
					const res = await forgetUserInfo(params)
					console.log('res', res)
					if (res.result == 0) {
						this.showSuccessModal = true;
						this.successTitle = "修改成功";
						uni.hideLoading()
						setTimeout(() => {
							this.showSuccessModal = false;
							uni.navigateBack({
								delta: 1
							})
						}, 1000)
					} else {
						uni.hideLoading()
						uni.$u.toast(res.message || '修改失败')
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			}
		}
	}
</script>

<style>
	/* @import url('login.css'); */
	.step-container {
		background-color: #f5f7fa;
		min-height: 100vh;
		padding: 20rpx;
		box-sizing: border-box;
	}
</style>